package cn.ywyself.extend.render;

import com.jfinal.render.Render;

import java.io.*;

/**
 * 导出txt文件
 *
 * @author : ywyself
 * @created : 2018-10-15 8:34
 */
public class TxtRender extends Render {

    /**
     * 文件内容
     */
    private String content;
    /**
     * 文件名
     */
    private String fileName;

    /**
     * @param content  文件内容
     * @param fileName 文件名，不包含扩展名
     */
    public TxtRender(String content, String fileName) {
        this.content = content;
        this.fileName = fileName + ".txt";
    }

    /**
     * Render to client
     */
    @Override
    public void render() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(getEncoding()), "ISO8859-1"));
            String contentType = request.getSession().getServletContext().getMimeType(fileName);
            response.setContentType(contentType != null ? contentType : "application/octet-stream");
            inputStream = new BufferedInputStream(new ByteArrayInputStream(content.getBytes("UTF-8")));
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            for (int len = -1; (len = inputStream.read(buffer)) != -1; ) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
